import path from 'path'
import { Plugin } from 'vite'

/** 扩展 `<Demo />` 组件 */
export default function demoPlugin(): Plugin {
  const demoCodeReg = /<Demo src=".+"\s*\/?>/
  const demoReg = /\/demo\/(\w|-|\/)+.md$/
  return {
    name: 'transform-demo',
    enforce: 'pre',
    transform(code, id) {
      if (demoCodeReg.test(code)) {
        let demoList = []
        const templates = code.replace(
          /<Demo src="(.*)"\s*(\/>|>.*<\/Demo>)/g,
          (_, $1) => {
            const component = /((\w|-)+)\/index\.md$/.exec(id)[1]
            const [__, demoext, demo] = /demo\/((.*)\.vue)$/.exec($1)
            demoList.push({
              demoPath: $1,
              componentName: `${component}/${demo}`,
              demoCode: `@/src/${component}/demo/${demoext}`,
            })
            return `<MobilePreview name="${component}/${demo}">
<Demo />
<template #code>

<<< @/src/${component}/demo/${demoext}

</template>
</MobilePreview>`
          },
        )
        const codes = `${templates}
<script setup lang="ts">
${demoList
  .map(({ demoPath }, i) => `import Demo${i} from '${demoPath}'`)
  .join('\n')}
</script>`
        return codes
      } else if (demoReg.test(id)) {
        const [_, component, __, demo] = /((\w|-)+)\/(\w+)\.md$/.exec(id)
        const componentPath = path.posix.resolve(
          `src/${component}/demo/${demo}.vue`,
        )
        const demoCode = `---
layout: false
---

<script setup lang="ts">
import { onBeforeMount, onMounted, ref } from 'vue';
import Demo from '${componentPath}'
import 'blogui-mobile-vue/styles/index.scss'
import styles from 'blogui-mobile-vue/styles/base.scss?inline'

onBeforeMount(() => {
  const style = document.createElement('style')
  style.textContent = styles
  document.head.appendChild(style)
})
const isMounted = ref(false)
onMounted(() => {
  isMounted.value = true
})
</script>

<Demo v-if="isMounted"/>
`
        return demoCode
      }
    },
  }
}
